package com.vcredit.creditcat.web.app;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.dubbo.config.annotation.Reference;
import com.vcredit.creditcat.api.ICreditCatProcessManager;
import com.vcredit.creditcat.api.ICustCardManager;
import com.vcredit.creditcat.dto.CustCardDto;
import com.vcredit.creditcat.enumtype.BankCardTypeEnum;
import com.vcredit.creditcat.exception.CustCardExcetpion;
import com.vcredit.creditcat.exception.DataException;
import com.vcredit.creditcat.model.Cust;
import com.vcredit.creditcat.util.EnumExtUtil;
import com.vcredit.creditcat.vo.BankCardBinParamVo;
import com.vcredit.creditcat.vo.BankCardBinVo;
import com.vcredit.creditcat.vo.BankCardListVo;
import com.vcredit.creditcat.vo.BankCardVo;
import com.vcredit.creditcat.vo.BindBankCardParamVo;
import com.vcredit.creditcat.vo.JsonResult;
import com.vcredit.creditcat.vo.QueryCardInput;
import com.vcredit.framework.annotation.Log;

@RestController
@RequestMapping("/card")
public class BankCardController extends BaseCreditCatController {

  @Reference(version = "1.0")
  private ICustCardManager custCardService;

  @Reference(version = "1.0")
  private ICreditCatProcessManager creditCatProcessManager;

  /**
   * 银行卡号解析 根据卡号返回银行信息
   * @author zhaoqi01
   * @param param
   * @return
   * @throws CustCardExcetpion
   */
  @Log
  @RequestMapping("/queryCardbin")
  public JsonResult<BankCardBinVo> queryBin(@RequestBody BankCardBinParamVo param)
      throws CustCardExcetpion {
    CustCardDto custCardDto = custCardService.queryCardBin(param.getBankCardNo());
    return JsonResult.SuccessResponse(new BankCardBinVo(custCardDto.getBankCode(), custCardDto
        .getBankName(), BankCardTypeEnum.DEBIT.equals(custCardDto.getCardType()) ? 1 : 0));
  }

  /**
   * 绑定银行卡
   * @author zhaoqi01
   * @param param
   * @param request
   * @param bResult
   * @return
   * @throws Exception
   */
  @Log
  @Valid
  @RequestMapping("/bindCard")
  public JsonResult<BankCardVo> bindCard(@RequestBody @Valid BindBankCardParamVo param,
      HttpServletRequest request, BindingResult bResult) throws Exception {
    Cust cust = super.getCust(request);

    // 校验验证码
    // if (2 == param.getOperationKind() && !super.checkVerifyCode(request,
    // param.getMobileNo(),
    // param.getAuthCodeSMS(), SendSmsTypeEnum.BindBankCard.getCode())) {
    // throw new CustCardExcetpion("验证码错误");
    // }

    String custName = cust.getCustName();
    String custIdno = cust.getCustIdno();

    // 查询卡bin是否为借记卡
    CustCardDto custCardDto = custCardService.queryCardBin(param.getBankCardNo());
    if (!BankCardTypeEnum.DEBIT.equals(custCardDto.getCardType())) {
      throw new CustCardExcetpion("请输入一张借记卡");
    }
    try {
      // 验卡
      param.setBankCode(param.getBankCode().toUpperCase());
      Boolean flag =
          custCardService.checkCustCard(custName, custIdno, param.getBankCardNo(),
              param.getMobileNo(), param.getBankCode());
      if (!flag) {
        throw new CustCardExcetpion("绑卡失败，请重新尝试");
      } else {
        CustCardDto cardDto =
            new CustCardDto(0l, param.getBankCode(), "", custCardDto.getCardType(),
                param.getBankCardNo(), custName, false, param.getMobileNo());
        // 绑卡
        cust.setCustName(custName);
        cust.setCustIdno(custIdno);
        cardDto = custCardService.bindCustCardAndItemDone(cust, cardDto);

        return JsonResult.SuccessResponse(new BankCardVo(String.valueOf(cardDto.getCardId())));
      }
    } catch (CustCardExcetpion e) {
      throw new CustCardExcetpion(e.getMessage());
    } catch (Exception re) {
      throw new CustCardExcetpion("绑卡失败，请重新尝试");
    }
  }

  /**
   * 获取用户银行卡列表
   * @author zhaoqi01
   * @param cardInput
   * @param request
   * @return
   * @throws Exception
   */
  @RequestMapping("/list")
  public JsonResult<BankCardListVo> queryCards(@RequestBody QueryCardInput cardInput,
      HttpServletRequest request) throws Exception {
    Integer cardType = cardInput.getCardType();
    if (null == cardType) {
      throw new DataException("参数为空");
    }
    if (null != cardType) {
      if (0 != cardType) {
        BankCardTypeEnum bankCardTypeEnum =
            EnumExtUtil.getEnumOnValue(BankCardTypeEnum.class, String.valueOf(cardType), "code");
        if (null == bankCardTypeEnum) {
          throw new DataException("参数错误");
        }
      }
    }
    BankCardTypeEnum bankCardTypeEnum =
        EnumExtUtil.getEnumOnValue(BankCardTypeEnum.class, String.valueOf(cardType), "code");
    List<CustCardDto> cards =
        custCardService.queyCardsByCustId(super.getCust(request).getCustId(), bankCardTypeEnum);
    List<BankCardVo> response = new ArrayList<BankCardVo>();
    for (CustCardDto card : cards) {
      response.add(new BankCardVo(String.valueOf(card.getCardId()), card.getBankName(), card
          .getAccountNo(), card.getBankCode(), card.getIsDefault(), card.getReservedMobile(), card
          .getCardType().getCode() == BankCardTypeEnum.DEBIT.getCode() ? true : false));
    }
    return JsonResult.SuccessResponse(new BankCardListVo(response));
  }
}
